package com.oa.android.activity;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.oa.android.R;
import com.oa.android.adapter.EmilAdapter;
import com.oa.android.adapter.PersonAdapter;
import com.oa.android.entry.Emil;
import com.oa.android.entry.Person;
import com.oa.android.utils.UConstants;
import com.oa.android.utils.Util;
import com.oa.android.view.XListView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 选择人
 *
 * @author -zouqh
 */
public class PersonActivity extends Activity implements OnClickListener, XListView.IXListViewListener {

    private ImageView close;
    private TextView title, searchCru, sure;
    private XListView listView;
    ProgressDialog dialog;
    private List<Person> emilList;
    private int page = 1;
    private int pageSize = 20;
    private int allPage = 0;
    private PersonAdapter adapter;
    private String keyword = "";
    private Map<Integer, String> map;
    private Map<Integer, String> mapID;
    private StringBuffer stringBuffer;
    private StringBuffer stringBuffer1;
    private int temp = 0;
    private int temp1 = 0;
    private LinearLayout layout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cao_gaox_activity);
        close = (ImageView) findViewById(R.id.close);
        title = (TextView) findViewById(R.id.title_text);
        searchCru = (TextView) findViewById(R.id.searchCru);
        sure = (TextView) findViewById(R.id.ritgh_text);
        layout=(LinearLayout)findViewById(R.id.layout);
        sure.setText("确定");
        searchCru.setHint("请输入姓名");
        sure.setVisibility(View.VISIBLE);
//        layout.setVisibility(View.GONE);
        listView = (XListView) findViewById(R.id.listView);
        title.setText("选择人员");
        stringBuffer = new StringBuffer();
        stringBuffer1 = new StringBuffer();
        map = new ConcurrentHashMap<>();
        mapID= new ConcurrentHashMap<>();
        listView.setPullLoadEnable(true);// 向上滑动加载更多开启
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(this);
        listView.setFooterName("", false);
        close.setOnClickListener(this);
        sure.setOnClickListener(this);
        searchCru.setOnClickListener(this);
        emilList = new ArrayList<>();
        adapter = new PersonAdapter(this, emilList);
        listView.setAdapter(adapter);
        getDate(keyword);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position--;
                Util.printLog("person--------------", position + "");
                CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkbox);
                checkBox.toggle();
                if (checkBox.isChecked()) {
                    map.put(position, emilList.get(position).getNAME());
                    mapID.put(position, emilList.get(position).getEMPID());
                } else {
                    for (Map.Entry entry : map.entrySet()) {

                        Object key = entry.getKey();
                        if (position == (int)key) {
                            map.remove(key);
                            mapID.remove(key);
                        }

                    }
                }

            }
        });

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        Intent intent;
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.searchCru:
                intent = new Intent(this, SearchActivity.class);
                startActivityForResult(intent, 1);
                break;

            case R.id.ritgh_text:
                temp = 0;
                temp1 = 0;
                if (map.size() > 0) {
                    if (map.size() == 1) {
                        Iterator i = map.entrySet().iterator();
                        while (i.hasNext()) {//只遍历一次,速度快
                            Map.Entry e = (Map.Entry) i.next();
                            stringBuffer.append(e.getValue());
                        }

                        Iterator ii = mapID.entrySet().iterator();
                        while (ii.hasNext()) {//只遍历一次,速度快
                            Map.Entry e = (Map.Entry) ii.next();
                            stringBuffer1.append(e.getValue());
                        }


                    } else {

                        Iterator i = map.entrySet().iterator();
                        while (i.hasNext()) {//只遍历一次,速度快
                            temp++;
                            Map.Entry e = (Map.Entry) i.next();
                            if (temp == 1) {
                                stringBuffer.append(e.getValue());
                            } else {
                                stringBuffer.append(",").append(e.getValue());
                            }

                        }

                        Iterator ii = mapID.entrySet().iterator();
                        while (ii.hasNext()) {//只遍历一次,速度快
                            temp1++;
                            Map.Entry e = (Map.Entry) ii.next();
                            if (temp1 == 1) {
                                stringBuffer1.append(e.getValue());
                            } else {
                                stringBuffer1.append(",").append(e.getValue());
                            }

                        }
                    }
                    intent = new Intent();
                    intent.putExtra("person", stringBuffer.toString());
                    intent.putExtra("personID", stringBuffer1.toString());
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    Toast.makeText(getApplicationContext(), "请选择人员！", Toast.LENGTH_SHORT).show();
                }

                break;

            default:
                break;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate(keyword);
                    } else {
                        listView.setFooterName("", false);
                    }
                    break;

            }

        }
    };


    //获人员列表
    private void getDate(String selstr) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.GET_PERSON_LIST);
        params.addBodyParameter("LKind", "OA");
        params.addBodyParameter("USNAME", UConstants.EmpName);
        params.addBodyParameter("SELSTR", selstr);
        params.addBodyParameter("PAGE", page + "");
        params.addBodyParameter("ROWS", pageSize + "");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / pageSize);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Person>>() {
                            }.getType();
                            List<Person> list = gson.fromJson(object.getString("rows").toString(), lt);
                            if (list != null && list.size() > 0) {
                                emilList.addAll(list);
                                adapter.notifyDataSetChanged();
                                if (page == allPage) {
                                    listView.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listView.setFooterVisibility(true);
                                }

                            } else {
                                Toast.makeText(x.app(), "暂无人员！", Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无人员！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listView.stopRefresh();
        listView.stopLoadMore();
        listView.setRefreshTime("刚刚");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    keyword = data.getStringExtra("keyword");
                    emilList.clear();
                    page = 1;
                    adapter.notifyDataSetChanged();
                    getDate(keyword);

                }
            }
        }

    }
}
